package horncomb.bpm.hrsm.interact;

import java.util.List;

import horncomb.bpm.BpmContextHolder;
import horncomb.bpm.task.core.TaskInstance;
import horncomb.bpm.task.instance.DefaultTaskInstance;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * 任务表单服务。
 * <p>
 * 用于为表现层展示任务信息，是表现层请求向流程请求转换的门面。
 * @author Daniel
 */
public class TaskFormService implements InitializingBean {

	/**
	 * {@inheritDoc}
	 */
	public void afterPropertiesSet() throws Exception {
	}

	// public Map<String, Object> showReference(TaskForm taskForm, Object form)
	// {
	// Map<String, Object> result = new HashMap<String, Object>();
	// return result;
	// }

	public void get(MockBizEditForm form) {
		Assert.notNull(form, "TaskForm must be not null!");
		String currentActor = BpmContextHolder.getContext().getCurrentActor();
		// DAO GET
		if (StringUtils.hasText(form.getTaskInstanceId())) {
			// 办理人，从待办进入（带有任务Id）。
			TaskInstance task = BpmContextHolder.getContext()
					.getTaskManagementServcie().findTaskInstance(
							form.getTaskInstanceId());
			form.setTaskInstance(task);
			// -> taskInstanceId
			// <- isSubmitable, isRedoable, currentActors
			// <-
			if (task.getEndDate() == null) {
				// 任务未完成
				if (currentActor.equals(task.getActor())) {
					form.setSubmitable(false);
				} else if (task.getCandidate() != null
						&& task.getCandidate().length > 0) {
					for (String actor : task.getCandidate()) {
						if (actor.equals(currentActor)) {
							// TODO 策略抽取
							// 自动获取任务,显示获取任务按钮
							task.setActor(currentActor);
							task.setCandidate(null);
							form.setSubmitable(false);
						}
					}
				}
			} else {

			}
		}
		// 非办理人，显示当前办理人
		List<String> currentActors = BpmContextHolder.getContext()
				.getTaskManagementServcie().findTodoTaskActorsInToken(
						form.getId());
	}
}
